import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 从localStorage初始化状态
  const userAccount = ref(JSON.parse(localStorage.getItem('userAccount')) || null)
  const token = ref(localStorage.getItem('token') || '')
  const isLogin = ref(JSON.parse(localStorage.getItem('isLogin')) || false)

  // 统一保存到localStorage的函数
  const saveToLocalStorage = () => {
    localStorage.setItem('userAccount', JSON.stringify(userAccount.value))
    localStorage.setItem('token', token.value)
    localStorage.setItem('isLogin', JSON.stringify(isLogin.value))
  }

  const setUser = (accountData, userToken) => {
    userAccount.value = accountData
    token.value = userToken
    isLogin.value = true
    saveToLocalStorage() // 保存到本地
  }

  const clearUser = () => {
    userAccount.value = null
    token.value = ''
    isLogin.value = false
    localStorage.clear() // 清空全部或指定key
  }

  const updateUserInfo = (newInfo) => {
    if (userAccount.value) {
      userAccount.value = { ...userAccount.value, ...newInfo }
      saveToLocalStorage() // 更新后保存
    }
  }

  return { userAccount, token, isLogin, setUser, clearUser, updateUserInfo }
})